package com.blue.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

/**
 * 压缩/解豆压缩工具类
 * 
 * @author zhengj
 * @since 1.0 2017年8月16日
 */
public class CompressUtil
{
	private static Logger logger = LoggerFactory.getLogger(CompressUtil.class);
	
	private CompressUtil()
	{
	}
	
	/**
	 * zip 压缩
	 * 
	 * @param data 待压缩的byte数组
	 * @return 压缩后的byte数组
	 */
	public static byte[] zip(byte[] data)
	{
		if (data == null || data.length == 0)
			return data;
		
		byte[] output = null;
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
				DeflaterOutputStream dos = new DeflaterOutputStream(baos))
		{
			dos.write(data, 0, data.length);
			dos.finish();
			dos.flush();
			output = baos.toByteArray();
		}
		catch (IOException e)
		{
			logger.error("压缩流出错－", e);
		}
		
		return output;
	}
	
	/**
	 * zip 解压缩
	 * 
	 * @param data 待解压缩的byte数组
	 * @return 解压缩后的byte数组
	 */
	public static byte[] unzip(byte[] data)
	{
		byte[] output = null;
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
				InflaterOutputStream ios = new InflaterOutputStream(baos))
		{
			ios.write(data, 0, data.length);
			ios.finish();
			ios.flush();
			output = baos.toByteArray();
		}
		catch (IOException e)
		{
			logger.error("解压缩流出错－", e);
		}
		
		return output;
	}
	
	
}
